<!-- 管理员 -->
<template>
  <div>
    <div>
      <!-- 搜索部分 -->
      <el-input
        clearable
        v-model.trim="configReq.username"
        @keyup.enter="getInfo"
        style="width: 250px; margin-right: 13px"
        placeholder="请输入管理员名称"
      />
      <el-button type="primary" :icon="Search" @click="getInfo">查找</el-button>
      <el-button
        type="primary"
        :icon="Edit"
        @click="
          () => {
            resetConfig();
            titleUpAdd = 0;
            dialogUpAdd = true;
          }
        "
        v-btn="'sys:admin:create'"
        >添加</el-button
      >
    </div>
    <div style="margin-top: 20px">
      <!-- 表格 -->
      <el-table :data="infoList" border>
        <el-table-column prop="id" label="管理员ID" width="100" />
        <el-table-column prop="username" label="管理员名称" width="180" />
        <el-table-column prop="realname" label="真实姓名" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column label="管理员角色">
          <template #default="{ row }">
            <el-tag v-for="item in row.roleIds" :key="item" style="margin: 5px">{{
    roleOptions.find((v: any) => v.value == item).label
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              @click="
                () => {
                  resetConfig();
                  titleUpAdd = 1;
                  Object.assign(adminDTO, scope.row);
                  dialogUpAdd = true;
                }
              "
              >修改</el-button
            >
            <el-button type="danger" @click="deleAdmin(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <!-- 添加和修改的弹出框 -->
      <el-dialog
        v-model="dialogUpAdd"
        :title="titleUpAdd == 0 ? '添加' : '编辑'"
        width="35%"
        destroy-on-close
      >
        <el-form ref="formRef" :model="adminDTO" :rules="rules" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input
              :disabled="titleUpAdd == 1"
              v-model.trim="adminDTO.username"
              type="text"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="1 != titleUpAdd">
            <el-input v-model.trim="adminDTO.password" type="text" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model.trim="adminDTO.phone" type="text" maxlength="11" />
          </el-form-item>
          <el-form-item label="真实姓名" prop="realname">
            <el-input v-model.trim="adminDTO.realname" type="text" />
          </el-form-item>
          <el-form-item
            label="角色"
            prop="roleIds"
            :rules="
              1 != titleUpAdd
                ? [{ required: false }]
                : [
                    {
                      message: '角色不能为空',
                      trigger: 'change',
                      required: true,
                    },
                  ]
            "
          >
            <!-- v-model绑定对应value值 -->
            <el-select
              v-model="adminDTO.roleIds"
              multiple
              filterable
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitForm(formRef)">{{
              titleUpAdd == 1 ? "修改" : "新增"
            }}</el-button>
            <el-button @click="resetForm(formRef)">重置</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <div style="margin: 20px 0px">
      <!-- 分页组件 -->
      <ElPagination
        :total="pageInfo.total"
        :limit="pageInfo.limit"
        @changeReq="changeConfig"
      ></ElPagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { post } from "@/request/http";
import { Search, Edit } from "@element-plus/icons-vue";
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from "element-plus";
import { number } from "@intlify/core-base";
// 数据部分
let id = ref(0); //点击行的管理员id
let infoList = ref([]); //管理员列表
let roleOptions: any = ref([]); //选择框角色列表
let titleUpAdd = ref(0); //添加和修改弹出框的标题
let formRef = ref<FormInstance>(); //添加和修改弹出框的标题
// 请求表格数据的配置
let configReq = reactive({
  _gp: "admin",
  _mt: "list",
  username: "", //管理员名称
  page: 1,
  limit: 20,
});
// 传给分页组件的数据
let pageInfo = reactive({
  limit: 20, //显示条数
  total: 0,
});
//添加和修改管理员的数据
let dataUpAdd = reactive({
  _gp: "admin",
  _mt: "",
});
let adminDTO = reactive({
  username: "",
  password: "",
  phone: "",
  realname: "",
  roleIds: [],
});
let dialogUpAdd = ref(false); // 显示添加和修改的弹出框

let validatePass = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入密码"));
  } else {
    if (value.length < 6) {
      callback(new Error("密码长度不能为小于6"));
    }
    callback();
  }
};
//用户名验证
let validateUser = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("用户名不能为空"));
  } else {
    callback();
  }
};
//手机号验证
let validatePho = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("手机号不能为空"));
  } else {
    var reg = /^[1]([3-9])[0-9]{9}$/;
    if (!reg.test(value)) {
      callback(new Error("手机号格式错误"));
    }
    callback();
  }
};
//真实姓名验证
let validateReal = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("真实姓名不能为空"));
  } else {
    var reg = /^[\u4e00-\u9fa5]+?$/;
    if (!reg.test(value)) {
      callback(new Error("真实姓名必须为中文"));
    }
    callback();
  }
};
let rules = ref({
  username: [{ validator: validateUser, trigger: "blur", required: true }],
  password: [{ validator: validatePass, trigger: "blur", required: true }],
  phone: [{ validator: validatePho, trigger: "blur", required: true }],
  realname: [{ validator: validateReal, trigger: "blur", required: true }],
});

// 方法部分
//  获取管理员数据的方法
const getInfo = () => {
  post(configReq)
    .then((res) => {
      if (200 == res.errno) {
        //成功状态码
        // console.log(res);
        infoList.value = res.data.items; //获取表格信息
        pageInfo.total = res.data.total; //获取总条数
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
// 分页切换触发
const changeConfig = (e: { page: number; limit: number }) => {
  Object.assign(configReq, e);
  getInfo();
};
// 获取角色信息的方法
const getRole = () => {
  post({
    _gp: "admin.role",
    _mt: "options",
  })
    .then((res) => {
      if (200 == res.errno) {
        //成功状态码
        roleOptions = res.data;
        // console.log( res.data)
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

onMounted(() => {
  getInfo();
  getRole();
});
// 删除管理员(点击确认)
const deleAdmin = (id: number) => {
  ElMessageBox.confirm("是否删除该管理员?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    post({
      _gp: "admin",
      _mt: "delete",
      id: id, //目标删除Id
    })
      .then((res) => {
        if (200 == res.errno) {
          //成功状态码
          ElMessage.success("删除成功");
          getRole();
          getInfo(); //刷新数据
        }
      })
      .catch((err) => {
        console.log(err);
      });
  });
};
// 提交表单(添加修改管理员)
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    //验证对应表单是否通过
    if (valid) {
      switch (titleUpAdd.value) {
        case 0:
          dataUpAdd._mt = "create";
          updataAdd();
          break;
        case 1:
          adminDTO.password = ""; //删除属性之后不提交密码
          dataUpAdd._mt = "edit";
          updataAdd();
          break;
      }
    }
  });
};
// 添加和修改共用的请求
const updataAdd = () => {
  post({ ...dataUpAdd, adminDTO: JSON.stringify(adminDTO) })
    .then((res) => {
      if (200 == res.errno) {
        //成功状态码
        dialogUpAdd.value = false; //关闭弹窗
        ElMessage.success("操作成功"); //提示信息
        getInfo(); //刷新数据
      }
    })
    .catch((err) => {
      dialogUpAdd.value = false; //关闭弹窗
      console.log(err);
      return;
    });
};
// 重置管理员添加和修改的配置
const resetConfig = () => {
  Object.assign(dataUpAdd, {
    _gp: "admin",
    _mt: "",
  });
  Object.assign(adminDTO, {
    username: "",
    password: "",
    phone: "",
    realname: "",
    roleIds: [],
  });
};
// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style></style>
